"""
本模块主要是Huffman编码相关，
生成DC_L,DC_C,AC_C,AC_L四张Huffman表格用于导出
"""
#保留前导零
def keepzero(length,num):
    string='{:0'+str(length)+'b}'
    b=string.format(num)
    return b



def huffman(Code_length):#通过Code_length列表传入 从2开始每个长度的code个数
    # Code_length=[3,1,1,1,1,1,1,1,1]#从2开始每个长度的code个数
    Category=[]
    code=0                                     #根据c（i）=2（c（i-1+1）推出整个Huffman表
    for i in range(len(Code_length)):
        for j in range(Code_length[i]):
            Category.append(keepzero(i+2,code))
            code += 1
        code=2*code
    return Category

def sort(list1):                    #把每一个长度归并为一个表，合成一个大表
    list2=huffman(list1)
    sort=[]
    i = 0
    for x in range(len(list1)):
        a = []
        for y in range(list1[x]):
           a.append(list2[i])
           i+=1
        sort.append(a)
    return sort

DC_L=huffman([1,5,1,1,1,1,1,1])
DC_C=huffman([3,1,1,1,1,1,1,1,1,1])


Codelength=[2,2,3,4,5,5,6,7,9,10,12,4,6,8,9,11,12,16,16,16,16,5,8,10,12,15,16,16,16,16,16,5,8,10,12,16,16,16,16,16,
16,6,9,16,16,16,16,16,16,16,16,6,10,16,16,16,16,16,16,16,16,7,11,16,16,16,16,16,16,16,16,7,11,16,16,16,16,16,16,16,
16,8,16,16,16,16,16,16,16,16,16,9,16,16,16,16,16,16,16,16,16,9,16,16,16,16,16,16,16,16,16,9,16,16,16,16,16,16,16,16,16,
9,16,16,16,16,16,16,16,16,16,11,16,16,16,16,16,16,16,16,16,14,16,16,16,16,16,16,16,16,16,10,15,16,16,16,16,16,16,16,16,16
]
CodeNum=[]
AC_C=[]
for x in range(16):
    CodeNum.append(0)
for x in range(len(Codelength)):
    CodeNum[Codelength[x] - 2]+=1  #统计每个长度的个数 CodeNum[0]记录的是2，接下来以此类推
p=sort(CodeNum)
for x in range(len(Codelength)):
    # Map.append(sort(CodeNum)[Codelength[x]-2][len(sort(CodeNum)[Codelength[x]-2])-(CodeNum[Codelength[x] - 2])])
    AC_C.append(p[Codelength[x] - 2][len(p[Codelength[x] - 2]) - (CodeNum[Codelength[x] - 2])])
    CodeNum[Codelength[x]-2]-=1
#按长度依次取出Huffman编码





#同理对AC_L再来操作一遍
Codelength=[4,2,2,3,4,5,7,8,10,16,16,4,5,7,9,11,16,16,16,16,16,5,8,10,12,16,16,16,16,16,16,6,9,12,16,16,16,16,16,16,16,6,10,16,16,16,16,16,16,16,16,7,11,16,16,16,16,16,
16,16,16,7,12,16,16,16,16,16,16,16,16,8,12,16,16,16,16,16,16,16,16,9,15,16,16,16,16,16,16,16,16,9,16,16,16,16,16,16,16,16,16,9,
16,16,16,16,16,16,16,16,16,10,16,16,16,16,16,16,16,16,16,10,16,16,16,16,16,16,16,16,16,11,16,16,16,16,16,16,16,16,16
,16,16,16,16,16,16,16,16,16,16,11,16,16,16,16,16,16,16,16,16,16]
CodeNum=[]
AC_L=[]
for x in range(16):
    CodeNum.append(0)
for x in range(len(Codelength)):
    CodeNum[Codelength[x] - 2]+=1
p=sort(CodeNum)
for x in range(len(Codelength)):
    # Map.append(sort(CodeNum)[Codelength[x]-2][len(sort(CodeNum)[Codelength[x]-2])-(CodeNum[Codelength[x] - 2])])
    AC_L.append(p[Codelength[x] - 2][len(p[Codelength[x] - 2]) - (CodeNum[Codelength[x] - 2])])
    CodeNum[Codelength[x]-2]-=1



def pointt(tuple):
    if tuple!=15:
        t=tuple[0]*10+tuple[1]
    else:
        t=tuple[0]*10+tuple[1]+1
    return t

#对于游程编码给出的元组，找到相对应的表中的索引